package edu.vital.energy.longevity.ch10.controller;

import edu.vital.energy.longevity.ch10.domain.Article;
import edu.vital.energy.longevity.ch10.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/articles")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    // 编辑文章页面
    @PostMapping
    public String addArticle(Article article, Model model) {
        List<Article> articles= articleService.insertArticle(article);
        model.addAttribute("articles", articles);
        return "article"; // 确认 editArticle.html 存在
    }
    // 查询所有文章
    @GetMapping
    public String findAllArticles(Model model) {
        List<Article> articles = articleService.findAllArticles();
        model.addAttribute("articles", articles);
        return "article";
    }

    // 根据ID查询文章
    @GetMapping("/view/{id}")
    public String findArticleById(@PathVariable("id") int id, Model model) {
        Article article = articleService.findArticleById(id);
        model.addAttribute("article", article);
        return "articleDetail"; // 确认 articleDetail.html 存在
    }

    // 编辑文章页面
    @GetMapping("/edit/{id}")
    public String editArticle(@PathVariable("id") int id, Model model) {
        Article article = articleService.findArticleById(id);
        model.addAttribute("article", article);
        return "editArticle"; // 确认 editArticle.html 存在
    }

    // 删除文章
    @GetMapping("/delete/{id}")
    public String deleteArticle(@PathVariable("id") int id) {
        articleService.deleteArticle(id);
        return "redirect:/articles";
    }
    // 删除文章
    @PostMapping("/update/{id}")
    public String updateArticle(@PathVariable("id") int id, Article article,Model model) {
        List<Article> articles = articleService.updateArticle(article);
        model.addAttribute("articles", articles);
        return "article";
    }

    // 搜索文章
    @GetMapping("/search")
    public String searchArticles(@RequestParam(required = false) String title, 
                                @RequestParam(required = false) String author, 
                                Model model) {
        List<Article> articles = articleService.searchArticles(title, author);
        model.addAttribute("articles", articles);
        return "article";
    }
}